<template>
  <el-dialog
    v-model="visibleDialog"
    :title="isUpdate ? '编辑' :'新增'"
    :visible.sync="visibleDialog"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleCancel"
  >
    <el-form ref="rowForm" :model="row" :rules="rules" label-width="100px" style="margin-right: 50px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="row.username"
          autocomplete="off"
          :disabled="isUpdate"
          maxlength="15"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item v-if="!isUpdate" label="密码" prop="password">
        <el-input
          v-model="row.password"
          type="password"
          autocomplete="off"
          show-password
          maxlength="15"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="row.phone"
          type="phone"
          autocomplete="off"
          :disabled="isUpdate"
          minlength="11"
          maxlength="11"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="row.nickname" autocomplete="off" maxlength="16" show-word-limit clearable/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="row.email" type="email" autocomplete="off" maxlength="30" show-word-limit clearable/>
      </el-form-item>
      <el-form-item label="角色" prop="roles">
        <el-select
          v-model="row.roles"
          value-key="id"
          placeholder="请选择角色"
          filterable
          multiple
          clearable
          style="display:block;"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :multiple="true"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像">
        <crop-image-upload v-model="row.avatar" :width="100" :height="100" :upload="handleUpload"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnSaveLoading" @click="handleSave(true)">保存并新增</el-button>
      <el-button type="primary" :loading="btnSaveLoading" @click="handleSave(false)">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import User from '@/api/entity/User'
import RoleService from '@/api/RoleService'
import UploadService from '@/api/UploadService'
import UserService from '@/api/UserService'
import CropImageUpload from '@/components/Upload/CropImageUpload'

export default {
  components: {CropImageUpload},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: User,
      required: true
    }
  },
  data() {
    return {
      btnSaveLoading: false,
      roleList: [],
      rules: Object.freeze({
        username: [
          {required: !this.isUpdate, message: '请输入登录用户名', trigger: 'blur'}
        ],
        password: [
          {required: !this.isUpdate, message: '请输入密码', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'}
        ],
        email: [{type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']}],
        phone: [
          {required: !this.isUpdate, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '必须是 11 位', trigger: ['blur']}
          // {
          //   validator: (rule, value, callback) => {
          //     if (!value) {
          //       callback()
          //     }
          //     if (/1[345789]\d{9}/.test(value)) {
          //       callback()
          //     } else {
          //       callback(new Error('必须是 11 位数字'))
          //     }
          //   }, trigger: 'blur'
          // }
        ],
        roles: [{required: true, message: '请选择角色', trigger: 'change'}]
      })
    }
  },
  computed: {
    visibleDialog: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    isUpdate: {
      get() {
        return (!!this.row.id)
      }
    }
  },
  // created() {
  //   this.handleOpen()
  // },
  // mounted() {
  //   console.log('mounted')
  // },
  // beforeUpdate() {
  //   console.log('beforeUpdate')
  //   console.log(this.$refs)
  //   // this.$refs['rowForm'].clearValidate()
  // },
  // updated() {
  //   console.log('updated')
  //   console.log(this.$refs)
  // },
  // created() {
  //   console.log(['created'])
  // },
  // mounted() {
  //   console.log(['mounted'])
  // },
  methods: {
    async handleOpen() {
      console.log(['handleOpen this.row', this.row])
      // this.$refs['rowForm'].clearValidate()
      const result = await RoleService.options()
      result
        .ifToastErrorMessage('角色列表加载失败')
        .ifSuccess(() => {
          this.roleList = result.data
          if (this.row.roles) { // 编辑时填充角色列表
            this.row.roles = this.roleList
              .filter(row => this.row.roles.includes(row.id))
              .map(row => row.id)
          }
        })
    },
    handleUpload(file) {
      return UploadService.uploadUserAvatar(file)
      // .then(result => result
      //   .dataFirst(row => onSuccess(row))
      //   .ifFailure(() => onError(`文件上传失败:${result.message}`))
      //   .ifDataEmpty(() => onError('文件上传成功，但服务器未返回文件信息'))
      // )
    },
    handleCancel() {
      this.$refs.rowForm.resetFields()
      this.$refs.rowForm.clearValidate()
      this.visibleDialog = false
    },
    /**
     *
     * @param saveAndNew {boolean} true：保存并新增 ； false：保存
     * @returns {Promise<void>}
     */
    async handleSave(saveAndNew) {
      const valid = await this.$refs.rowForm.validate()
      if (!valid) {
        return
      }
      this.btnSaveLoading = true
      console.log(['this.row', this.row])
      const result = await (this.isUpdate ? UserService.update(this.row) : UserService.save(this.row)).finally(() => (this.btnSaveLoading = false))
      result
        .ifToastMessage('保存成功', '保存失败')
        .ifSuccess(() => {
          this.$emit('ok')
          if (saveAndNew) { // 清理不需要保留的值
            this.row.id = null
            this.row.phone = null
            this.row.username = null
            this.row.email = null
          } else {
            this.handleCancel()
          }
        })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
